<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax-POST请求</title>
    <style>
        #result{
            width: 300px;
            height: 100px;
            border: 1px solid #cccccc;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td>城市Id：</td>
            <td>
                <input id="cid" type="text">
            </td>
        </tr>
        <tr>
            <td>城市名称：</td>
            <td>
                <input id="cname" type="text">
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <button id="btn">添加</button>
            </td>
        </tr>
    </table>
    <div id="result"></div>
    <script>
        let cid = document.getElementById('cid')
        let cname = document.getElementById('cname')
        let btn = document.getElementById('btn')
        let result = document.getElementById('result')
        btn.onclick = function(){
            //01.创建ajax对象
            let xhr = new XMLHttpRequest()
            //02.初始化请求
            xhr.open('POST','http://localhost:3000/addCity?name=张三')
            //设置请求头
            //Content-Type 是设置请求体内容的类型
            //application/x-www.form-urlencoded 是参数查询字符串的类型
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')

            //03.发送请求（post请求的参数，通常都是设置在send中）
            xhr.send(`cid=${cid.value}&cname=${cname.value}`)
            //04.监听状态事件
            xhr.onreadystatechange = function(){
                if(xhr.readyState===4){
                    if(xhr.status===200){
                        result.innerHTML = xhr.response
                    }
                }
            }
        }
    </script>
</body>
</html>